import { getSMS, loginAPI } from '@/api'
// import { LoginForm, Token,  } from '@/types/data'
import { LoginForm } from '@/types/data'
import { getStorage, removeStorage, setStorage } from '@/utils/loaclStorage'
import { refreshAPI } from '@/utils/request'
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'

// Token
export type Token = {
  token: string | null
  refresh_token?: string | null
}

export const TOKEN_KEY = 'token'
export const REFRESH_TOKEN_KEY = 'refresh_token'

// redux获取登陆token
export const loginAction = createAsyncThunk(
  'user/login',
  async (data: LoginForm) => {
    try {
      const res = await loginAPI(data)
      return res.data.data
    } catch (error) {}
  }
)

// redux无感刷新
export const refreshAction = createAsyncThunk(
  'user/refresh',
  async (refreshToekn:string) => {
    try {
      const res = await refreshAPI(refreshToekn)
      console.log('res',res);
      return res.data.data
    } catch (error) {}
  }
)

// redux发送短信验证码
export const getSMSAction = createAsyncThunk(
  'user/getSMS',
  async (mobile: string) => {
    try {
      await getSMS(mobile)
    } catch (error) {}
  }
)

const initialState = {
  token: getStorage(TOKEN_KEY),
  refresh_token: getStorage(REFRESH_TOKEN_KEY)
} as Token

export const loginSlice = createSlice({
  name: 'login',
  initialState,
  reducers: {
    logoutAction:(state)=>{
      removeStorage(TOKEN_KEY)
      removeStorage(REFRESH_TOKEN_KEY)
      state.token = null 
      state.refresh_token = null 
    }
  },
  extraReducers: {
    [loginAction.fulfilled.type]: (state, action: PayloadAction<Token>) => {
      state.token = action.payload.token
      state.refresh_token = action.payload.refresh_token
      setStorage(TOKEN_KEY, state.token)
      setStorage(REFRESH_TOKEN_KEY, state.refresh_token)
    },
    // 请求刷新token后,存入redux之中
    [refreshAction.fulfilled.type]:(state, action: PayloadAction<Token>)=>{
      state.token = action.payload.token
      setStorage(TOKEN_KEY, action.payload.token)
    }
  }
})
// Action creators are generated for each case reducer function
export const { logoutAction } = loginSlice.actions

export default loginSlice.reducer
